#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ftp://ftp.sbooth.org/sorting_helper.rb
# http://wiki.rubyonrails.org/rails/pages/Sort+Helper
module SortingHelper

  class Sorter

    def initialize(controller, columns, sort, order = 'ASC', default_sort = 'id', default_order = 'ASC')
      sort            = default_sort unless columns.include? sort
      order           = default_order unless ['ASC', 'DESC'].include? order

      @controller     = controller
      @columns        = columns
      @sort           = sort
      @order          = order
      @default_sort   = default_sort
      @default_order  = default_order
    end

    def to_sql
      @sort + ' ' + @order
    end

    # if +column+ is the current selected order, return 'ASC' or 'DESC', else return nil
    def column_order(column)
      column = @default_sort unless @columns.include?(column)

      if column == @sort
        order = @order
      else
        order = nil
      end
      order
    end

    # little view helper to create the name of the class for the column
    # by default return tablesort_none, tablesort_asc, tablesort_desc depending on whether column is ordered or not
    def column_order_class(column, classname = 'tablesort', separator = '_', notordered='none')
      order = column_order(column)
      classname + separator + (order.nil? ? notordered : order.downcase)
    end

    def to_link(column, params={})
      column = @default_sort unless @columns.include?(column)

      if column == @sort
        order = ('ASC' == @order ? 'DESC' : 'ASC')
      else
        order = @default_order
      end

      { :params => { 'sort' => column, 'order' => order }.merge(params) }
      # or is it ?? cf bug report
      # { :params => params.merge({ ‘sort’ => column, ‘order’ => order }) }
    end

  end

end
